require "open4"

module Wondercap
module CapistranoMixins
  
  module Syscmd

    def syscmd_status(command, output_io = nil, no_log = false)
      logger.info("executing locally: #{command.to_a.join ' '}")
      
      Open4::popen4(*command.to_a) do |pid, stdin, stdout, stderr|
        stdin.close
        
        out_thread = Thread.start {
          loop do
            line = stdout.readline
            output_io.write line if output_io
            logger.info "> #{line}" unless no_log
          end rescue ""
        }
        err_thread = Thread.start {
          loop do
            line = stderr.readline
            logger.debug "err> #{line}" unless no_log
          end rescue ""
        }

        out_thread.join
        err_thread.join
      end
    end
    
    def syscmd(command, output_io = nil, no_log = false)
      if (status_code = syscmd_status(command, output_io, no_log)) != 0
        raise "command failed (#{status_code}): #{command}" 
      end
    end
    
    def syscmd_output(command, no_log = false)
      output = StringIO.new
      syscmd(command, output, no_log)
      output.string
    end    
    
  end
  
end
end